//
//  BBIntoAnimation.swift
//  BBAnimatedTransitioning
//
//  Created by YouMao on 2022/4/29.
//

import UIKit

/// 进入动画
public enum BBIntoAnimation {
    case `default`
    case view(_ view:UIView, from:CGRect)
}

// MARK: - Animation Methods
extension BBIntoAnimation {
    
    // 默认动画
    func defaultAnimation(_ transitionContext: UIViewControllerContextTransitioning, duration: TimeInterval) {
        let containerView = transitionContext.containerView
        if let fromeView = transitionContext.view(forKey: .from) {
            containerView.addSubview(fromeView)
        }
        guard let toView = transitionContext.view(forKey: .to) else { return }
        toView.frame = CGRect(x: containerView.bounds.size.width, y: toView.frame.origin.y, width: toView.frame.size.width, height: toView.frame.size.height)
        containerView.addSubview(toView)
        UIView.animate(withDuration: duration, delay: 0, options: []) {
            toView.frame = CGRect(x: 0, y: toView.frame.origin.y, width: toView.frame.size.width, height: toView.frame.size.height)
        } completion: { finished in
            if finished {
                transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
            }
        }
    }
    
    /// 某个view的移动效果
    func viewFromFrame(_ transitionContext: UIViewControllerContextTransitioning, duration: TimeInterval, view:UIView, from:CGRect) {
        let containerView = transitionContext.containerView
        
        if let fromeView = transitionContext.view(forKey: .from) {
            containerView.addSubview(fromeView)
        }
        
        guard let toView = transitionContext.view(forKey: .to) else {
            return
        }
        let originalColor = toView.backgroundColor
        toView.backgroundColor = originalColor?.withAlphaComponent(0.1)
        containerView.addSubview(toView)
        let originalFram = view.frame
        view.frame = from
        
        UIView.animate(withDuration: duration, delay: 0, options: []) {          toView.backgroundColor = originalColor
            view.frame = originalFram
        } completion: { finished in
            if finished {
                transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
            }
        }
    }
}

// MARK: - BBTransitiontingAnimatorDelegate
extension BBIntoAnimation: BBTransitiontingAnimatorDelegate {
    
    public func implement(_ transitionContext: UIViewControllerContextTransitioning, duration: TimeInterval) {
        switch self {
        case .default:
            defaultAnimation(transitionContext, duration: duration)
        case .view(let view, from: let frame):
            viewFromFrame(transitionContext, duration: duration, view: view, from: frame)
        }
    }
}
